package com.wfw.service.impl;

import com.wfw.dto.OrderMasterDto;
import com.wfw.enums.OrderStatusEnum;
import com.wfw.enums.PayStatusEnum;
import com.wfw.enums.ResultEnum;
import com.wfw.exception.SellException;
import com.wfw.mapper.OrderDetailMapper;
import com.wfw.mapper.OrderMasterMapper;
import com.wfw.model.OrderDetail;
import com.wfw.model.OrderMaster;
import com.wfw.model.ProductInfo;
import com.wfw.service.OrderService;
import com.wfw.service.ProductInfoService;
import com.wfw.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMasterMapper orderMasterMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductInfoService productInfoService;

    @Override
    public synchronized String create(OrderMasterDto orderMasterDto) {
        List<OrderDetail> orderDetailList=orderMasterDto.getOrderDetailList();
        BigDecimal orderAmount=new BigDecimal(BigInteger.ZERO);
        String orderId=KeyUtil.genUniqueKey();
        orderMasterDto.setOrderId(orderId);
        //1.查询商品的数量、价格
        for (OrderDetail orderDetail:orderDetailList) {
            ProductInfo productInfo=productInfoService.findOne(orderDetail.getProductId());
            if (productInfo==null||productInfo.getProductId()==null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //2.订单详情入库
            orderDetail.setProductPrice(productInfo.getProductPrice());
            orderDetail.setProductName(productInfo.getProductName());
            orderDetail.setProductIcon(productInfo.getProductIcon());
            orderDetail.setOrderId(orderMasterDto.getOrderId());
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderAmount=orderDetail.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);//计算总价
            orderDetailMapper.insertSelective(orderDetail);
        }

        //3.写入订单数据库（orderMaster和orderDetail）
        OrderMaster orderMaster=orderMasterDto.convertFor();
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterMapper.insertSelective(orderMaster);

        //4.扣库存
        productInfoService.decreaseStock(orderDetailList);

        return orderMasterDto.getOrderId();
    }

    @Override
    public OrderMasterDto findOne(String orderId) {
        OrderMasterDto orderMasterDto=new OrderMasterDto();

        OrderMaster orderMaster=orderMasterMapper.selectByPrimaryKey(orderId);
        if (orderMaster==null||orderMaster.getOrderId()==null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList=orderDetailMapper.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)||orderDetailList.size()<=0){
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        BeanUtils.copyProperties(orderMaster,orderMasterDto);
        orderMasterDto.setOrderDetailList(orderDetailList);
        return orderMasterDto;
    }

    @Override
    public List<OrderMaster> findList(String buyerOpenid) {
        return orderMasterMapper.findByBuyerOpenid(buyerOpenid);
    }

    @Override
    public OrderMasterDto cancel(OrderMaster orderMaster) {
        //orderMaster应至少包含orderId和buyerOpenid
        if (orderMaster.getBuyerOpenid()==null||orderMaster.getOrderId()==null){
            throw new SellException(ResultEnum.LACK_PARAM);
        }
        OrderMasterDto orderMasterDto=findOne(orderMaster.getOrderId());
        //判断订单状态,如果不是新下单则不能取消
        if (!orderMasterDto.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            throw new SellException(ResultEnum.ORDER_STATUS_ERROE);
        }

        if (!orderMasterDto.getBuyerOpenid().equals(orderMaster.getBuyerOpenid())){
            throw new SellException(ResultEnum.ORDER_OPENID_ERROR);
        }

        //修改订单状态
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        orderMasterDto.setOrderStatus(OrderStatusEnum.CANCEL.getCode());


        //回滚库存
        if (CollectionUtils.isEmpty(orderMasterDto.getOrderDetailList())||orderMasterDto.getOrderDetailList().size()<=0){
            log.error("[取消订单]订单中无商品详情");
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        productInfoService.increaseStock(orderMasterDto.getOrderDetailList());

        //如果已支付，退款
        if (orderMasterDto.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())){
            //TODO 退款操作
            orderMaster.setPayStatus(PayStatusEnum.CANCEL.getCode());
            orderMasterDto.setPayStatus(PayStatusEnum.CANCEL.getCode());
        }

        int resultCount=orderMasterMapper.updateByPrimaryKeySelective(orderMaster);
        if (resultCount<=0){
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderMasterDto;
    }

    @Override
    public OrderMasterDto finish(OrderMasterDto orderMasterDto) {
        return null;
    }

    @Override
    public OrderMasterDto paid(OrderMasterDto orderMasterDto) {
        return null;
    }

}
